package netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import netty.protocol.Hello;

@Slf4j
public class ProtoServerHandler extends SimpleChannelInboundHandler<Hello.Protocol> {

    public ProtoServerHandler() {
        log.info(">>> init {}", this.toString());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Hello.Protocol protocol) throws Exception {
        try {
            // Do something with msg
            log.info("receive data: {}, {}", protocol.getType(), ctx.channel().remoteAddress());

            if (protocol.getType() == Hello.Protocol.DataType.Chat) {
                log.info(">>> chat {}", protocol);
            } else if (protocol.getType() == Hello.Protocol.DataType.Join) {
                log.info(">>> join {}", protocol);
            } else if (protocol.getType() == Hello.Protocol.DataType.Leave) {
                log.info(">>> leave {}", protocol);
            } else {
                log.info(">>> error protocol {}", protocol);
            }
        } finally {
//            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}